package org.dromara.common.websocket.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.utils.ServletUtils;
import org.dromara.common.websocket.domain.BoardWebSocketMessage;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.net.URI;
import java.util.HashMap;
import java.util.Map;

import static org.dromara.common.websocket.constant.WebSocketConstants.BOARD_CLIENT_KEY;

/**
 * WebSocket握手请求的拦截器
 *
 * @author zendwang
 */
@Slf4j
public class BoardWebSocketInterceptor implements HandshakeInterceptor {

    /**
     * 处理板子请求 携带客户端的uuid
     *
     * @return
     */
    private static boolean boardHandle(ServerHttpRequest request, Map<String, Object> attributes) {
        URI uri = request.getURI();
        String query = uri.getQuery();
        // 解析请求参数
        String[] params = query.split("&");
        Map<String, String> attributeMap = new HashMap<>();
        for (String param : params) {
            String[] keyValue = param.split("=");
            String key = keyValue[0];
            String value = keyValue.length > 1 ? keyValue[1] : null;
            attributeMap.put(key, value);
        }
        String boardClientKey = attributeMap.get(BOARD_CLIENT_KEY);
        if (boardClientKey == null) {
            return false;
        }
        BoardWebSocketMessage boardWebSocketMessage = new BoardWebSocketMessage();
        boardWebSocketMessage.setBoardId(boardClientKey);
        boardWebSocketMessage.setBoardIp(ServletUtils.getClientIP());
        attributes.put(BOARD_CLIENT_KEY, boardWebSocketMessage);
        return true;
    }

    /**
     * 握手前
     *
     * @param request    request
     * @param response   response
     * @param wsHandler  wsHandler
     * @param attributes attributes
     * @return 是否握手成功
     */
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) {
        return boardHandle(request, attributes);
    }

    /**
     * 握手后
     *
     * @param request   request
     * @param response  response
     * @param wsHandler wsHandler
     * @param exception 异常
     */
    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {

    }
}
